package xin.marcher.module.construction.service.impl;

import org.springframework.stereotype.Service;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.utils.ParamCheckUtil;
import xin.marcher.module.construction.domain.dto.AttributeDetailDTO;
import xin.marcher.module.construction.domain.dto.AttributeResultDTO;
import xin.marcher.module.construction.domain.request.AttributeRequest;
import xin.marcher.module.construction.domain.request.QueryAttributeRequest;
import xin.marcher.module.construction.repository.AttributeRepository;
import xin.marcher.module.construction.service.AttributeService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 规格服务
 */
@Service
public class AttributeServiceImpl implements AttributeService {

    @Resource
    private AttributeRepository attributeRepository;

    /**
     * 新增/编辑规格键值接口
     *
     * @param request
     * @return
     */
    @Override
    public AttributeResultDTO saveAttribute(AttributeRequest request) {
        // 入参检查
        this.checkAttributeRequestParam(request);

        // 保存规格信息
        attributeRepository.saveAttribute(request);

        return new AttributeResultDTO(Boolean.TRUE);
    }

    /**
     * 新增/编辑规格键值接口
     *
     * @param request
     * @return
     */
    @Override
    public AttributeResultDTO updateAttribute(AttributeRequest request) {
        // 入参检查
        this.checkAttributeRequestParam(request);

        // 保存规格信息
        attributeRepository.updateAttribute(request);

        // 返回结果
        return new AttributeResultDTO(Boolean.TRUE);
    }

    /**
     * 查询规格键值信息
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<AttributeDetailDTO> pageAttribute(QueryAttributeRequest request) {
        PageResult<AttributeDetailDTO> pageResult = new PageResult<>(attributeRepository.getAttributeDetail(request));
        pageResult.setTotalElements(attributeRepository.countAttributeDetail(request));
        pageResult.setSize(request.getPageSize());

        Long totalPage = pageResult.getTotalElements() % pageResult.getSize() > 0 ?
                pageResult.getTotalElements() / pageResult.getSize() + 1 :
                pageResult.getTotalElements() / pageResult.getSize();

        pageResult.setTotalPages(totalPage);
        return pageResult;
    }

    private void checkAttributeRequestParam(AttributeRequest request) {
        ParamCheckUtil.checkObjectNonNull(request);

        // 规格键信息
        AttributeRequest.AttributeKeyRequest attributeKeyRequest = request.getAttributeKeyRequest();
        ParamCheckUtil.checkObjectNonNull(attributeKeyRequest);

        // 规格值信息
        List<AttributeRequest.AttributeValueRequest> attributeValueRequests = request.getAttributeValueRequests();
        ParamCheckUtil.checkCollectionNonEmpty(attributeValueRequests);
    }
}
